import React, {FC, useEffect, useState} from 'react'
import {useHistory, useParams} from "react-router";
import './index.css'
import {Button, Form, Input, message, Modal, Select, Table, Tag, TreeSelect,} from "antd";
import {useRequest} from "@umijs/hooks";
import {fetchRequest} from "@/utils/Request";
import {url} from "@/utils/url";
import {EditOutlined, ExclamationCircleOutlined, SearchOutlined, SyncOutlined} from "@ant-design/icons";
import TableToolbar from "@/components/TableSetting/TableToolbar";

const {confirm} = Modal;
const {Option} = Select

const {SHOW_PARENT} = TreeSelect;

const CurriculumStudent: FC<any> = (props) => {

    const {id} = useParams<any>();

    //启动或者关闭
    const {run: openRun} = useRequest((params) => fetchRequest(url.OPEN_RULE_STATE, params), {
        manual: true,
        onSuccess: async (result, params: any) => {
            if (result.success) {

                message.success(result.data)
            } else {

                message.error(result.errorMsg)
            }
        }

    })

      //启动或者关闭
      const {run: allPush} = useRequest((params) => fetchRequest(url.STUDENT_RULE_KEY, params), {
        manual: true,
        onSuccess: async (result, params: any) => {
            if (result.success) {

                message.success(result.data)
            } else {

                message.error(result.errorMsg)
            }
        }

    })

    const onAllPush=async ()=>{
        confirm({
            title: '提示',
            icon: <ExclamationCircleOutlined/>,
            content: `是否要推送？`,
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            async onOk() {
                await allPush({
                    ruleId:id
                })
                refresh()

            
            },
        });
        
    }

    const {
        tableProps,
        run,
        refresh
    } = useRequest(((current, params) => fetchRequest(url.GET_RULE_STATE_TABLE, {
        pageSize: current.pageSize,
        pageStart: current.current,
        ...params

    })), {
        paginated: true,
        manual: true,
        formatResult: (response: any) => {
            return {
                list: response.data?.rows,
                total: response.data?.total,
                success: response.success,
                errorMsg: response.errorMsg
            };
        }
    })

    const columns = [
        {
            title: '学生姓名',
            dataIndex: 'studentName',
            key: 'studentName',
        },
        {
            title: '适用范围',
            dataIndex: 'deptName',
            key: 'deptName',
        },
        {
            title: '下发状态',
            dataIndex: 'remark',
            key: 'remark',

        },


        {
            title: '状态',
            render: (item: any) => {
                console.log(item)
                return <><Tag color={item.color}>{item.stateName}</Tag></>
            }
        },
        {
            title: ()=>{
                return <>
                     操作
                     <Tag color="#52c41a" style={{marginLeft:'20px'}} onClick={onAllPush}>一键推送</Tag>
                </>
            },
            render: (item: any) => {


                const title = `${item.state == '2' || item.state == '5' || item.state == '4' ? '启用' : '停用'}`
                const flag = item.state == '2' || item.state == '5' || item.state == '4' ? 1 : 0
                const color = flag ? '#52c41a' : '#ff0000'


                const list = []

                if (item.state == 1 || item.state == 5||item.state==4) {
                    list.push({
                        title: title,
                        color: color,
                        icon: <EditOutlined/>,
                        onClick: () => {

                            confirm({
                                title: '提示',
                                icon: <ExclamationCircleOutlined/>,
                                content: `是否${title}该条规则？`,
                                okText: '确定',
                                okType: 'danger',
                                cancelText: '取消',
                                async onOk() {
                                    await openRun({
                                        ruleId: id, flag,
                                        state: item.state,
                                        userId: item.userId
                                    })
                                    await refresh()
                                },
                            });


                        }
                    },)
                }


                return <>
                    {list.map(item => <Tag key={item.title} {...item}>{item.title}</Tag>)}
                </>
            }
        }
    ]

    const onFinish = (values: any) => {
        run({pageSize: 10, current: 1}, {...values, ruleId: id})
    }
    useEffect(() => {
        run({pageSize: 10, current: 1}, {ruleId: id})
    }, [id])


    return <div className={'wrap'}>
        <Search onFinish={onFinish}/>
        <div className={'curriculum-table-wrap'}>
            <Table {...tableProps as any} rowKey={'userId'} columns={columns}/>
        </div>

    </div>
}

const Search: FC<{ onFinish: (values: any) => void, }> = ({onFinish}) => {
    const [form] = Form.useForm();
    const [treeNode, setTreeNode] = useState<any>([]);
    const [classValue, setClassValue] = useState<any>([])


    const loadData = async ({treeId, level}: any) => {

        await getSchoolOrganizationRequest({treeId, level: level + 1})

    };

    //请求在校学生组织机构
    async function getSchoolOrganizationRequest(params: any) {
        try {
            const json = await fetchRequest(url.GET_SCHOOL_ORGANIZATION, params);

            console.log(json)
            if (json.success) {
                message.destroy();
                const list = json.data.map((item: any) => {
                    let temp
                    delete item.children;

                    temp = {...item, pId: item.parentId, id: item.treeId, value: item.value}
                    return temp
                });


                if (params.level === 0) {
                    setTreeNode(list);
                } else {
                    setTreeNode((data: any) => {
                        return [...data, ...list]
                    })
                }


            } else {
                message.destroy();
                message.error(json.errorMsg)
            }
        } catch (error: any) {
            message.destroy();
            message.error(error.message)

        }

    }

    const onChange = (value: any) => {
        setClassValue(value)

        console.log(value)

    }

    const [requestParamTree] = useState<any>(
        {
            "level": 0,
            "treeId": "0"
        }
    );

    const tProps = {
        treeData: treeNode,
        value: classValue,
        loadData,
        onChange,
        treeDataSimpleMode: true,
        showCheckedStrategy: SHOW_PARENT,
        placeholder: '请选择班级范围',
        style: {
            width: '100%',
        },
    }

    const onReset = () => {
        form.resetFields();
        onFinish({})

    }

    useEffect(() => {
        getSchoolOrganizationRequest(requestParamTree)
    }, [requestParamTree])


    return <div className={'curriculum-search'}>
        <Form form={form} layout={'inline'} onFinish={onFinish}>


            <Form.Item label="学生姓名" name={'studentName'}>
                <Input placeholder="请输入学生姓名"/>
            </Form.Item>


            <Form.Item label="组织机构" name={'deptId'} style={{width: 300}}>
                <TreeSelect  {...tProps}/>
            </Form.Item>

            <Form.Item>

                <Button key="1" type="primary" icon={<SearchOutlined/>} htmlType="submit"
                        style={{marginRight: '8px'}}>搜索</Button>
                <Button key="2" icon={<SyncOutlined/>} onClick={onReset}>重置</Button>

            </Form.Item>
        </Form>
    </div>
}

export default CurriculumStudent
